package com.sun.showcase.biz.basic.service.impl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sun.showcase.biz.basic.dao.UploadFileDao;
import com.sun.showcase.biz.basic.service.FileDealService;
import com.sun.showcase.biz.basic.service.FtpClientService;
import com.sun.showcase.biz.basic.utils.FtpClientConstants;
import com.sun.showcase.client.basic.domain.UploadFile;
@Service("fileDealService")
public class FileDealServiceImpl implements FileDealService {
	
	@Resource
	private UploadFileDao uploadFileDao;
	
	@Resource
	private FtpClientService ftpClientService;//远程服务客户端
	@Resource
	private FtpClientConstants ftpClientConstants;
	
	private final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");//时间格式
	

	private static final int BUFFERED_SIZE = 4 * 1024;
	
	public void setUploadFileDao(UploadFileDao dao) {
		this.uploadFileDao = dao;
	}
	public void setFtpClientService(FtpClientService ftpClientService) {
		this.ftpClientService = ftpClientService;
	}
	
	public UploadFile saveFile(File file,UploadFile upload) {
        
		if(file == null) return upload;
		
        String savaFileName = format.format(new Date())+upload.getFileName().substring(upload.getFileName().lastIndexOf("."));
        
        upload.setSaveFileName(savaFileName);
        
        uploadFileDao.save(upload);
        
        //系统文件
        if(upload.getType()==1)saveToSys(file,savaFileName);
        //远程
        else ftpClientService.saveFile(file,upload);
        
		return upload;
	}
	public UploadFile saveFileAsStream(BufferedInputStream fiStream,UploadFile upload) {
        
        String savaFileName = format.format(new Date())+upload.getFileName().substring(upload.getFileName().lastIndexOf("."));
        
        upload.setSaveFileName(savaFileName);
        
        uploadFileDao.save(upload);
        if(upload.getType()==1) {
        	//系统文件
        	saveToSys(fiStream,savaFileName);
        }else{
        	//远程
        	ftpClientService.saveFileAsStream(fiStream,upload);
        }
        
        //记录数据库信息
        
		return upload;
	}
	public UploadFile findFile(String id) {
		
		return uploadFileDao.getById(Long.parseLong(id));
	}

	public InputStream findFile(UploadFile upload,OutputStream output) {
		
		InputStream input = null;
		
        if(1==upload.getType()){
        	
        	File file = new File(ftpClientConstants.getDisk() + File.separator + upload.getSaveFileName());
        	
        	try{
        		
				input = new FileInputStream(file);
				
			}catch(FileNotFoundException e){
				
				e.printStackTrace();
			}
        }else{
        	ftpClientService.findByFile(upload,output);
        }
        	
		return input;
	}
	public void deleteFile(String id) {
		
		UploadFile upload = findFile(id);
		
		//删除数据库文件
		uploadFileDao.deleteById(Long.parseLong(id));
		if(upload == null){
			return;
		}
		//系统文件
        if(upload.getType()==1){
        	//删除文件系统文件
			File file = new File(ftpClientConstants.getDisk() + File.separator + upload.getSaveFileName());
			
			file.delete();
        }
        //远程
        else ftpClientService.deleteFile(upload);

	}

	public List<UploadFile> getByIds(List<Long> list) {
		return uploadFileDao.getByIds(list);
	}
	
	//文件上传到服务器目录下
	private void saveToSys(File file, String fileName){
		
		File outFile = new File(ftpClientConstants.getDisk() + File.separator + fileName);
		
		copy(file,outFile);
	}
	
	private boolean copy(File file,File target){
		
		boolean flag = false;
		
        InputStream in = null;
        
        OutputStream out = null;
        
        try {
            in = new BufferedInputStream(new FileInputStream(file), BUFFERED_SIZE);
            
            out = new BufferedOutputStream(new FileOutputStream(target), BUFFERED_SIZE);
            
            byte[] bs = new byte[BUFFERED_SIZE];
            
            int i;
            
            while ((i = in.read(bs)) > 0) {
            	
                    out.write(bs, 0, i);
                    
            }
        }catch (Exception e){
        	
        	e.printStackTrace();
        	
        	flag = false;
        }finally{
        	
            try {
            	
                if (in != null){
               	 in.close();
                 }
                
                if (out != null){
                	
               	 out.close();
               	 
                }
                
            }catch (Exception e){
            	
            	e.printStackTrace();
            }
        }

        return flag;
	 }
	//文件上传到服务器目录下
	private void saveToSys(BufferedInputStream fiStream, String fileName){
		File outFile = new File(ftpClientConstants.getDisk() + File.separator + fileName);
		
		copy(fiStream,outFile);
	}
	private boolean copy(BufferedInputStream fiStream,File target){
		
		boolean flag = false;
		
        InputStream in = null;
        
        OutputStream out = null;
        
        try {
            in = fiStream;
            
            out = new BufferedOutputStream(new FileOutputStream(target), BUFFERED_SIZE);
            
            byte[] bs = new byte[BUFFERED_SIZE];
            
            int i;
            
            while ((i = in.read(bs)) > 0) {
            	
                    out.write(bs, 0, i);
                    
            }
        }catch (Exception e){
        	
        	e.printStackTrace();
        	
        	flag = false;
        }finally{
        	
            try {
            	
                if (in != null){
               	 in.close();
                 }
                
                if (out != null){
                	
               	 out.close();
               	 
                }
                
            }catch (Exception e){
            	
            	e.printStackTrace();
            }
        }

        return flag;
	 }
	@Override
	public InputStream findAttach(UploadFile upload) {
		InputStream input = null;
        if(1==upload.getType()){
        	File file = new File(ftpClientConstants.getDisk() + File.separator + upload.getSaveFileName());
        	try {
				input = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				
				e.printStackTrace();
			}
        }else{
        	input = ftpClientService.findAttach(upload);
        }
        	
		return input;
	}
	@Override
	public OutputStream findAttachOut(UploadFile upload) {
		// TODO Auto-generated method stub
		return null;
	}
	
}
